package me.android.library.utils.android;


import android.app.Activity;
import android.app.Application;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@UtilityClass
public final class ContextUtil {
    private WeakReference<Context> appContextRef;
    private WeakReference<Activity> currentActivityRef;
    private final Handler MAIN_HANDLER = new Handler(Looper.getMainLooper());

    /**
     * 初始化工具类，应在 Application.onCreate() 中调用
     */
    public void init(@NonNull Application application) {
        appContextRef = new WeakReference<>(application);

        // 注册 Activity 生命周期回调，用于获取当前 Activity
        application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                setCurrentActivity(activity);
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
                setCurrentActivity(activity);
            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                setCurrentActivity(activity);
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {
                // Activity 暂停时，不立即清除引用，避免在 onResume 前出现空值
            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {
                // 当前 Activity 停止时，如果它与引用的 Activity 相同，则清除引用
                if (getCurrentActivity() == activity) {
                    clearCurrentActivity();
                }
            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
                // 无需处理
            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                // Activity 销毁时，如果它与引用的 Activity 相同，则清除引用
                if (getCurrentActivity() == activity) {
                    clearCurrentActivity();
                }
            }
        });
    }

    /**
     * 获取应用级 Context（即 ApplicationContext）
     * 可安全用于需要 Context 的静态方法中，不会导致内存泄漏
     */
    @NonNull
    public Context getAppContext() {
        Context context = appContextRef != null ? appContextRef.get() : null;
        if (context == null) {
            throw new IllegalStateException("ContextUtils not initialized. Call ContextUtils.init() in Application.onCreate()");
        }
        return context;
    }

    /**
     * 获取当前可见的 Activity
     * 注意：在某些情况下可能返回 null（如应用在后台时）
     */
    @Nullable
    public Activity getCurrentActivity() {
        return currentActivityRef != null ? currentActivityRef.get() : null;
    }

    /**
     * 在主线程执行任务
     */
    public void runOnUiThread(@NonNull Runnable runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            // 当前线程是主线程，直接执行
            runnable.run();
        } else {
            // 否则，将任务 post 到主线程
            MAIN_HANDLER.post(runnable);
        }
    }

    /**
     * 获取资源对象
     */
    @NonNull
    public Resources getResources() {
        return getAppContext().getResources();
    }

    public ContentResolver getContentResolver(){
        return getAppContext().getContentResolver();
    }

    /**
     * 根据资源 ID 获取字符串
     */
    @NonNull
    public String getString(int resId) {
        return getAppContext().getString(resId);
    }

    /**
     * 根据资源 ID 获取字符串，并格式化
     */
    @NonNull
    public String getString(int resId, Object... formatArgs) {
        return getAppContext().getString(resId, formatArgs);
    }

    private void setCurrentActivity(@NonNull Activity activity) {
        currentActivityRef = new WeakReference<>(activity);
    }

    private void clearCurrentActivity() {
        if (currentActivityRef != null) {
            currentActivityRef.clear();
            currentActivityRef = null;
        }
    }
}